package cmd

import (
	"fmt"
	"im-tools/internal/config"
	"im-tools/internal/model"
	"im-tools/internal/service"
	"net/http"

	"github.com/duke-git/lancet/netutil"
	"github.com/goccy/go-json"
	"github.com/gookit/color"
	"github.com/spf13/cobra"
)

var groupJoinCmd = &cobra.Command{
	Use:   "joinGroup",
	Short: "加入群",
	Long:  `通过手机号加入群`,
	Run: func(cmd *cobra.Command, args []string) {
		var groupId string
		// var userId string
		var phone string
		for {
			color.Info.Println("输入群ID:")
			if _, err := fmt.Scanln(&groupId); err != nil {
				continue
			}

			color.Info.Println("输入手机号:")
			if _, err := fmt.Scanln(&phone); err != nil {
				continue
			}

			if groupId != "" && phone != "" {
				break
			}
		}

		joinGroup(groupId, phone)
	},
}

func joinGroup(groupId, phone string) {
	request := &netutil.HttpRequest{
		RawURL: config.API + "/api/zkim/group/inviteToJoinTheGroup",
		Method: "POST",
	}

	headers := http.Header{}
	headers.Add("Content-Type", "application/json")
	headers.Add("satoken", Token)
	request.Headers = headers

	us := service.UserService{}

	userIds := []model.GroupMember{}

	users := us.SelectUsersLike(phone)
	for _, u := range users {
		userIds = append(userIds, model.GroupMember{
			UserId:   u.FakeUid,
			Nickname: u.Nickname,
		})
		color.Info.Printf("添加成员: %s [%s]\n", u.FakeUid, u.Nickname)
	}

	joinGroupReq := &model.GroupJoinReq{
		InviteToGid: groupId,
		Members:     userIds,
		SrcFrom:     "0", //通过邀请
	}

	postData, err := json.Marshal(joinGroupReq)
	if err != nil {
		color.Error.Println(err)
	}
	request.Body = postData
	httpClient := netutil.NewHttpClient()
	resp, err := httpClient.SendRequest(request)
	if err != nil || resp.StatusCode != 200 {
		color.Error.Println(resp.StatusCode)
		return
	}
	color.Info.Printf("加入群结束 %v\n", resp.StatusCode)
}

func init() {
	rootCmd.AddCommand(groupJoinCmd)
}
